package listener;

import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionAttributeListener;
import jakarta.servlet.http.HttpSessionBindingEvent;

@WebListener
public class OnlineCountListener implements HttpSessionAttributeListener {
    private static int onlineCount = 0;
    
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        // 当添加 user 属性时（用户登录成功）
        if ("user".equals(event.getName())) {
            onlineCount++;
            event.getSession().getServletContext()
                .setAttribute("onlineCount", onlineCount);
        }
    }
    
    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        // 当移除 user 属性时（用户退出登录）
        if ("user".equals(event.getName()) && onlineCount > 0) {
            onlineCount--;
            event.getSession().getServletContext()
                .setAttribute("onlineCount", onlineCount);
        }
    }
    
    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        // 不需要处理属性替换的情况
    }
    
    public static int getOnlineCount() {
        return onlineCount;
    }
} 